package com.frinder.akka;

import akka.actor.UntypedActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.Random;


/**
 * Created by frinder on 2017/7/26.
 */
@Component
@Scope("prototype")
public class WorkerActor extends UntypedActor {

    private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);

    private int age;

    public WorkerActor() {
    }

    public WorkerActor(int age) {
        this.age = age;
    }

    @Override
    public void onReceive(Object message) throws Throwable {
        if (message instanceof AkkaRequest) {
            logger.info("{}, {}", message, this);
            getSender().tell(new AkkaResponse(AkkaResponse.Code.SUCCESS, ((AkkaRequest) message).getMessage()), getSelf());
            Thread.sleep(new Random().nextInt(1000));
        } else {
            unhandled(message);
        }
    }

    @Override
    public String toString() {
        return "WorkerActor{" +
                "age=" + age +
                "} " + super.toString();
    }
}
